'use client'
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import BlogPost from '@/components/BlogPost';
import { getArticleById } from '@/services/articleService';
import { Article } from '@/types/article';
import { Category } from '@/types/category';

interface ArticleDetailContentProps {
  id: string;
}

// 类型转换函数：将Article转换为BlogCard需要的格式
const convertToBlogPost = (article: Article) => {
  // 同步获取分类名称，避免使用异步函数
  const getCategoryName = (): string => {
    try {
      const item = localStorage.getItem('categories');
      if(item){
        const categories = JSON.parse(item);
        const category = categories.find((cat: Category) => cat.id === article.categoryId);
        return category?.name || '未分类';
      }
    } catch (error) {
      console.error('获取分类信息失败:', error);
    }
    return '未分类';
  };

  return {
    id: article.id,
    title: article.title,
    excerpt: article.excerpt || article.content.substring(0, 150) + '...',
    author: article.author?.username || '未知作者',
    date: new Date(article.createdAt).toISOString().split('T')[0],
    authorAvatar: article.author?.avatar || 'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixlib=rb-1.2.1&q=80&w=1080',
    category: getCategoryName(),
    tags: article.tags?.map(tag => tag.name) || [],
    image: article.coverImage || 'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixlib=rb-1.2.1&q=80&w=1080',
    readTime: Math.ceil((article.content?.length || 0) / 500) + '分钟阅读',
    viewCount: article.viewCount || 0,
    likeCount: article.likeCount || 0,
    content: article.content,
  };
};

const ArticleDetailContent: React.FC<ArticleDetailContentProps> = ({ id }) => {
  const router = useRouter();
  const [article, setArticle] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  useEffect(() => {
    // 滚动到页面顶部
    window.scrollTo(0, 0);

    // 获取文章详情
    const fetchArticle = async () => {
      try {
        setLoading(true);
        // 使用专门的getArticleById方法获取单篇文章
        const articleData = await getArticleById(Number(id));
        const convertedArticle = convertToBlogPost(articleData);
        setArticle(convertedArticle);
        
        // 增加文章浏览量
        // await increaseViewCount(Number(id)).catch(err => {
        //   console.error('增加浏览量失败:', err);
        // });
      } catch (err) {
        console.error('获取文章详情失败:', err);
        setError('获取文章失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchArticle();
  }, [id]);

  const handleBack = () => {
    router.back();
  };

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 text-center">
        <div className="w-16 h-16 border-4 border-gray-200 border-t-blue-500 rounded-full animate-spin mx-auto mb-4"></div>
        <p className="text-gray-500">加载中...</p>
      </div>
    );
  }

  if (error || !article) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 text-center">
        <p className="text-gray-500 mb-4">{error || '文章不存在'}</p>
        <button 
          onClick={handleBack}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
        >
          返回
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <BlogPost post={article} onBack={handleBack} />
    </div>
  );
};

export default ArticleDetailContent;